package fourfaith.com.ff_sl21_app.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.nineoldandroids.view.ViewHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fourfaith.com.ff_sl21_app.R;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.ItemAnimation;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;
import fourfaith.com.ff_sl21_app.utils.task.TaskMgr;


public class RemoteConfigListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    // 设置底部布局
    private static final int TYPE_FOOTER = 0;
    // 设置默认布局
    private static final int TYPE_DEFAULT = 1;

    // 上下文
    private Context context;
    private LayoutInflater mInflater;
    // 数据源
    private List<Map<String,Object>> items ;
    private RecyclerView recyclerView;
    private View viewRecycler;

    private Map<String, JSONObject> stsmtask;

    // 判断是不是最后一个item，默认是true
    private boolean mShowFooter = true;

    private int dimensionPixelSize = 0;

    public RemoteConfigListAdapter(Context context, List<Map<String,Object>> items, RecyclerView recyclerViews) {

        this.dimensionPixelSize = context.getResources().getDimensionPixelSize(R.dimen.bottom_item_height_min);
        this.context = context;
        this.items = items;
        this.mInflater = LayoutInflater.from(context);
        this.recyclerView = recyclerViews;
        this.stsmtask = new HashMap<>();
    }

    // 设置数据并刷新
    public void setData(List<Map<String,Object>> Data)
    {
        this.items = Data;
        this.notifyDataSetChanged();
    }

    // 设置不同的item
    @Override
    public int getItemViewType(int position)
    {
        // 判断当前位置+1是不是等于数据总数（因为数组从0开始计数），是的就加载底部布局刷新，不是就加载默认布局
        if (position + 1 == getItemCount())
        {
            return TYPE_FOOTER;
        } else
        {
            return TYPE_DEFAULT;
        }
    }


    // 设置布局（相当于设置convertView）
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {

        if (viewType == TYPE_DEFAULT)
        {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_remote_config_list_item, parent, false);

            DefaultViewHolder vh = new DefaultViewHolder(v);
            v.setTag(vh);
            return vh;
        } else
        {
            // 实例化布局
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_footer, null);
            // 代码实现加载布局
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            return new FooterViewHolder(view);
        }
    }

    // 在布局中加载数据（绑定数据）
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position)
    {
        // 用来在运行时指出对象是某一个对象
        if (holder instanceof DefaultViewHolder)
        {
            Map<String,Object> item = items.get(position);
            if (item == null)
            {
                return;
            }

            //数据填充
            ((DefaultViewHolder) holder).deviceStatus.setImageResource((Integer)item.get("deviceStatus"));
            ((DefaultViewHolder) holder).deviceName.setText(Constants.getString(item.get("deviceName")));
            ((DefaultViewHolder) holder).devicelayout.setTag(position);

            Object obj = items.get(position).get("isOpen");
            boolean isOpen = false;
            if(obj!=null) isOpen = (boolean)items.get(position).get("isOpen");

            if(isOpen)
            {
                ViewHelper.setRotation(((DefaultViewHolder) holder).detailImg, 90f);
                ((DefaultViewHolder) holder).deviceDetailLayout.getLayoutParams().height = dimensionPixelSize;
                ((DefaultViewHolder) holder).deviceDetailLayout.setVisibility(View.VISIBLE);
            }else{
                ViewHelper.setRotation(((DefaultViewHolder) holder).detailImg, 0f);
                ((DefaultViewHolder) holder).deviceDetailLayout.getLayoutParams().height = 0;
                ((DefaultViewHolder) holder).deviceDetailLayout.setVisibility(View.GONE);
            }

            ((DefaultViewHolder) holder).devicelayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    int position = (Integer) v.getTag();
                    Map<String, Object> item = items.get(position);

                    Object obj = item.get("isOpen");
                    boolean isOpen = false;
                    if(obj!=null) isOpen = (boolean)item.get("isOpen");
                    item.put("isOpen", !isOpen);

                    ViewGroup itemView = (ViewGroup) v.getParent();
                    DefaultViewHolder songViewHolder = (DefaultViewHolder) itemView.getTag();

                    ItemAnimation.rotateSwitcherIcon(songViewHolder.detailImg, item, 90);
                    if(!isOpen) {
                        ItemAnimation.show(songViewHolder.deviceDetailLayout,dimensionPixelSize);
                    }
                    else{
                        ItemAnimation.hide(songViewHolder.deviceDetailLayout,dimensionPixelSize);
                    }

                }
            });


            /**
             * 查询状态
             */
            ((DefaultViewHolder) holder).button_status.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Map<String, Object> item = items.get(position);

                    final int packettype = Integer.parseInt(String.valueOf(item.get("packettype")));
                    final String stcd = String.valueOf(item.get("deviceCode"));
                    TaskMgr taskMgr = TaskMgr.getInstance(context);
                    taskMgr.packettype = packettype;
                    //判断是否缓存了该设备的报送类型
                    if(stsmtask.containsKey(stcd)){
                        JSONObject jsonObject = stsmtask.get(stcd);
                        taskMgr.stsmtaskObj = jsonObject;
                        taskMgr.getStatus(stcd);
                    }else{
                        taskMgr.showProgressDialog();
                        String userId = Constants.getUserId();

                        String url = Constants.getAllFactorByStcd +"?userId=" + userId + "&stcd="+stcd;

                        RequestQueue mQueue = RequestQueueSingleton.getInstance(context).getRequestQueue();
                        JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.GET, url, ResponseResult.class,
                                new Response.Listener<ResponseResult>() {
                                    @Override
                                    public void onResponse(ResponseResult responseResult) {
                                        if (responseResult.getCode().equals("200")) {

                                            JSONObject dataObj = (JSONObject) responseResult.getData();

                                            stsmtask.put(stcd,dataObj);
                                            TaskMgr taskMgr = TaskMgr.getInstance(context);
                                            taskMgr.stsmtaskObj = dataObj;
                                            taskMgr.getStatus(stcd);

                                        } else {
                                            Toast.makeText(context, responseResult.getMsg(), Toast.LENGTH_SHORT).show();
                                        }


                                    }

                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                if (error.networkResponse == null) {
                                    Toast.makeText(context, "连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
                                } else {
                                    if (error.getMessage() == null) {
                                        Toast.makeText(context, "接口服务器异常", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
                                    }
                                }

                            }

                        });
                        mQueue.add(jsonRequest);

                    }

                }

            });

            /**
             * 查询版本
             */
            ((DefaultViewHolder) holder).button_version.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    Map<String, Object> item = items.get(position);

//					Toast toast = Toast.makeText(DeviceActivity.this, "查询版本" +map.toString(), Toast.LENGTH_SHORT);
//					toast.show();

                    TaskMgr taskMgr = TaskMgr.getInstance(context);
                    taskMgr.getVersion(String.valueOf(item.get("deviceCode")));

                }

            });

            /**
             * 远程配置
             */
            ((DefaultViewHolder) holder).button_distance.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    Map<String, Object> item = items.get(position);
//
//					Toast toast = Toast.makeText(DeviceActivity.this, "远程配置" +map.toString(), Toast.LENGTH_SHORT);
//					toast.show();

                    TaskMgr taskMgr = TaskMgr.getInstance(context);
                    taskMgr.getSetInfo(String.valueOf(item.get("deviceCode")));

                }

            });

            /**
             * 报警设置
             */
            ((DefaultViewHolder) holder).button_alarm.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    Map<String, Object> item = items.get(position);

//					Toast toast = Toast.makeText(DeviceActivity.this, "报警设置" +map.toString(), Toast.LENGTH_SHORT);
//					toast.show();

                    TaskMgr taskMgr = TaskMgr.getInstance(context);
                    taskMgr.getAlarmSetInfo(String.valueOf(item.get("deviceCode")));
                }

            });

        }
    }

    // 获取数据数目
    @Override
    public int getItemCount()
    {
        // 判断是不是显示底部，是就返回1，不是返回0
        int begin = mShowFooter? 1 : 0;
        // 没有数据的时候，直接返回begin
        if (items == null)
        {
            return begin;
        }
        // 因为底部布局要占一个位置，所以总数目要+1
        return items.size() + begin;
    }

    // 设置是否显示底部加载提示（将值传递给全局变量）
    public void isShowFooter(boolean showFooter)
    {
        this.mShowFooter = showFooter;
    }

    // 判断是否显示底部，数据来自全局变量
    public boolean isShowFooter()
    {
        return this.mShowFooter;
    }


    // 底部布局的ViewHolder
    public class FooterViewHolder extends RecyclerView.ViewHolder
    {
        public FooterViewHolder(View view)
        {
            super(view);
        }
    }

    // 默认布局的ViewHolder
    public class DefaultViewHolder extends RecyclerView.ViewHolder
    {
        public RelativeLayout devicelayout;
        public TextView deviceName;
        public ImageView deviceStatus,detailImg;
        public LinearLayout deviceDetailLayout;

        public Button button_status;
        public Button button_version;
        public Button button_distance;
        public Button button_alarm;

        public DefaultViewHolder(View itemView)
        {
            super(itemView);
            devicelayout = (RelativeLayout) itemView.findViewById(R.id.devicelayout);
            deviceName = (TextView) itemView.findViewById(R.id.deviceName);
            deviceStatus = (ImageView)itemView.findViewById(R.id.deviceStatus);
            detailImg = (ImageView)itemView.findViewById(R.id.detailImg);
            deviceDetailLayout = (LinearLayout)itemView.findViewById(R.id.deviceDetailLayout);

            button_status = (Button) itemView.findViewById(R.id.button_status);
            button_distance = (Button) itemView.findViewById(R.id.button_distance);
            button_version = (Button) itemView.findViewById(R.id.button_version);
            button_alarm = (Button) itemView.findViewById(R.id.button_alarm);

        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
}
